import user from '../../../utils/user.js'
import {
    base64ToWxfile,
    urlTobase64,
    wxfileTobase64,
    wait,
    toast
} from '../../../utils/util.js'
import { workDetailEcho } from '../../api/recruit'
import {
    createClientQrCode,
    getUserAvatar,
    getEnterpriseList,
} from '../../../api/app.js'
import Canvas from '../../../utils/canvas'
Page({
    data: {
        selectTypeList: [{
            text: '全选',
            callback: 'selectAll'
        }
        ],
        posterList:[],
        qrcode:'',
        isPoster:false,
        currentIndex:0,
        avatarUrl:'',
        userName:'',
        enterprise:{
            name:'',
            code:'',
            phone:'',
            userName:'',
            id:'',
            qrId:'',
            area:''
        },
        tipList:'',
        isSendOutBtn:false,
        qrId:'', // 二维码id
        jobInfo:{},// 岗位信息
        width:0,
        height:0,
        topFile:'',
        jobId:'',
        tabXWidth:40,
        companyName:'' //劳务公司名称
    },
    async onLoad(options) {
        console.log(options,'options')
        this.setData({
            jobId:options.id,
            companyName:user.companyName
        })
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        await this.setData({
            avatarUrl:user.avatarUrl,
            userName:user.userName
        })
        user.waitLogin().then(async()=>{
            const result = await workDetailEcho({
                jobId:options.id
            })
            let arr = []
            result.jobTag = result.jobTag.split(';')
            if(result.params.jobFile){
                arr = result.params.jobFile.filter(item=>{
                    return item.fileType == 'photo'
                })
            }
            if(arr.length){
                urlTobase64(arr[0].fileUrl).then(res=>{
                    base64ToWxfile(res,Math.ceil(Math.random() * 10000000000) + '.png').then(path=>{
                        console.log(path,'path')
                        this.setData({
                            topFile:path
                        })
                    })
                })
            }
            this.setData({
                jobInfo:result,
            })
            console.log(this.data.topFile,'topFile')
            await this.createInviteQrCode()
        })
    },
    async onUnload(){
        console.log('生命周期卸载')
        setTimeout(()=>{
            wx.hideLoading()
        },1000)
    },
    onNameInput(event){
        const { value } = event.detail
        this.setData({
            ['enterprise.userName']:value
        })
    },
    onPhoneInput(event){
        const { value } = event.detail
        this.setData({
            ['enterprise.phone']:value
        })
    },
    onEnterpriseInput(event){
        const { value } = event.detail
        getEnterpriseList({
            name:value
        }).then(res=>{
            this.setData({
                tipList:res
            })
        })
    },
    onTapEnter(event){
        console.log(event,'event')
        const { name,code,area } = event.currentTarget.dataset
        this.setData({
            ['enterprise.name']:name,
            ['enterprise.code']:code,
            ['enterprise.area']:area,
            tipList:[],
            isSendOutBtn:true
        })
        console.log(this.data.isSendOutBtn,'isSendOutBtn')
    },
    isSendOut(){
        if(this.data.enterprise.userName&&this.data.enterprise.phone&&this.data.enterprise.code){
            this.setData({
                isSendOutBtn:true
            })
            console.log(this.data.isSendOutBtn)
        }
    },
    onSwiperChange(event){
        console.log(event.detail.current,'event')
        this.setData({
            currentIndex:event.detail.current
        })
    },
    createInviteQrCode() {
        
        let scene =  ''
        scene = 'id=' + this.data.jobId + '&uid=' + user.userId + '&cid=' + user.companyId
        console.log(scene,'scene')
        createClientQrCode({
            page: 'pages/job-detail/job-detail',
            width: 100,
            scene: scene,
        }).then(res => {
            // console.log(res,'二维码')
            this.setData({
                ['enterprise.qrId']:res.qrId,
                qrId:res.qrId
            })
            let qrCode = res // 后台返回的base64图片流
            base64ToWxfile(qrCode, Math.ceil(Math.random() * 10000000000) + '.png').then(path => {
                this.setData({
                    qrcode: path
                },()=>{
                    console.log(this.data.qrcode,'qrcode')
                })
                if(this.data.topFile){
                    console.log('有图片')
                    this.saveQrCode()
                }else{
                    console.log('没图片')
                    this.saveQrCodeMini()
                }
            })
        })
    },
    async saveQrCodeMini(){
        let bg=[
            '/packageRecruit/assets/img/poster/poster1-mini.png',
            '/packageRecruit/assets/img/poster/poster2-mini.png',
            '/packageRecruit/assets/img/poster/poster3-mini.png'
        ]
        console.log(user.userId,'userid')
        const result = await  getUserAvatar({userId: user.userId})
        const path = await base64ToWxfile(result, 'avatar.png')
        this.setData({
            avatarUrl:path
        },()=>{
            console.log(this.data.avatarUrl,'avatarUrl')
        })
        
        for(const index in bg){
            wx.getImageInfo({
                src:bg[index],
                success:(res=>{
                    console.log(res,'width高')
                    this.data.width = res.width
                    this.data.height = res.height
                })
            })
            wx.showLoading({
                mask: true,
                title: '正在渲染中...',
                complete(res){
                    console.log('res',res)
                }
            })
            const ctx = wx.createCanvasContext('myCanvas')
            const canvas = new Canvas(ctx)
            canvas.roundRectColor(0,0,320,600,32,'#ffffff')
            // 背景图
            ctx.fillStyle = '#fff'
            canvas.drawHeightCutImage(0,0,320,310,310,bg[index])
            // 白色背景图 
            let jobTagLngth = this.data.jobInfo.jobTag.length
            canvas.roundRectColor(15,15,290,110,16,'#ffffff')
            // 岗位招聘标题
            canvas.fillText(this.data.jobInfo.jobName,30,40,'#2E3242',12,'left',true)
            // 灰色卡片 120
            console.log(this.data.jobInfo.jobTag.length,'this.data.jobInfo.jobTag.length')
            canvas.roundRectColor(30,50,260,60,8,'#FAFAFC')
            canvas.fillText(this.data.jobInfo.serveCompanyName.length > 10 ? (this.data.jobInfo.serveCompanyName.slice(0,13) + '...') : this.data.jobInfo.serveCompanyName,40,70,'#202536',10,'left')
            canvas.fillText(this.data.jobInfo.salary + this.data.jobInfo.jobSalaryType,280,70,'#FF7642',10,'right')
            let keyLeft = 40
            
            for(const i in this.data.jobInfo.jobTag){
                canvas.roundRectColor(keyLeft,85,((this.data.jobInfo.jobTag[i].length + 1) * 10),15,0,'#FAEDEC')
                canvas.fillText(this.data.jobInfo.jobTag[i],keyLeft + (this.data.jobInfo.jobTag[i].length * 13) / 2,95 ,'#FF7642',8,'center')
                console.log(i,keyLeft,'标签')
                keyLeft += (this.data.jobInfo.jobTag[i].length + 1) * 10 + 10
            }
            await wait(100)
            // 底部介绍卡片
            canvas.roundRectColor(15,140,20,90,12,'#ffffff')
            canvas.roundRectColor(285,140,20,90,12,'#ffffff')
            canvas.roundRectColor(20,140,279,90,0,'#ffffff')
            // 头像
            canvas.drawRoundImage(30,150,30,path,'#ffffff')
            // 姓名 // 换成劳务公司名称 
            canvas.fillText(user.companyName.length > 10 ? (user.companyName.slice(0,13) + '...') : user.companyName ,65,168,'#202536',10,'left',true)
            // 提示
            canvas.fillText('1对1服务 靠谱好工作',30,196,'#9497B1',10,'left')
            // 二维码 
            await wait(100)
            canvas.drawHeightCutImage(220,150,70,70,70,this.data.qrcode)
            // 提示扫码 
            canvas.drawHeightCutImage(30,206,120,15,15,'/packageRecruit/assets/img/poster/tips.png')
            canvas.fillText('子弹saas提供技术支持',160,275,'#fff',10,'center')
            ctx.draw(true)
            ctx.restore()
            await wait(100)
            await wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 320,
                height: 300,
                canvasId: 'myCanvas',
                success: async(res)=> {
                    console.log(res,'转换成功',bg[index])
                    await wxfileTobase64(res.tempFilePath,true).then(async url=>{
                        // console.log(url,'url')
                        let arr = []
                        arr = this.data.posterList
                        arr.push({
                            path:res.tempFilePath,
                            src:url
                        })
                        console.log(arr,'arrarrarr',arr.length)
                        if(arr.length ===3 ){
                            wx.hideLoading()
                        }
                        // console.log(res,'res')
                        await this.setData({
                            posterList:arr,
                        },()=>{
                            // console.log(this.data.posterList,'posterList')
                        })
                    })
                }
            })
        }
    },
    async saveQrCode() {
        let bg= [
            '/packageRecruit/assets/img/poster/poster1.png',
            '/packageRecruit/assets/img/poster/poster2.png',
            '/packageRecruit/assets/img/poster/poster3.png'
        ]
        console.log(user.userId,'userid')
        const result = await  getUserAvatar({userId: user.userId})
        const path = await base64ToWxfile(result, 'avatar.png')
        this.setData({
            avatarUrl:path
        },()=>{
            console.log(this.data.avatarUrl,'avatarUrl')
        })    
        
        for(const index in bg){
            wx.getImageInfo({
                src:bg[index],
                success:(res=>{
                    console.log(res,'width高')
                    this.data.width = res.width
                    this.data.height = res.height
                })
            })
            wx.showLoading({
                mask: true,
                title: '正在渲染中...',
                complete(res){
                    console.log('res',res)
                }
            })
            const ctx = wx.createCanvasContext('myCanvas')
            const canvas = new Canvas(ctx)
            canvas.roundRectColor(0,0,320,600,32,'#ffffff')
            // 背景图
            ctx.fillStyle = '#fff'
            canvas.drawHeightCutImage(0,0,320,600,600,bg[index])
            // 白色背景图
            canvas.roundRectColor(15,15,290,320,16,'#ffffff')
            // 头部图片 topFile this.data.topFile[0].fileUrl || '../../assets/img/poster/default.png'
            canvas.drawHeightCutImage(30,30,260,150,150,this.data.topFile || '../../assets/img/poster/default.png')
            // await wait(100)
            // 岗位招聘标题
            canvas.fillText(this.data.jobInfo.jobName,30,206,'#2E3242',14,'left')
            // 灰色卡片 120
            console.log(this.data.jobInfo.jobTag.length,'this.data.jobInfo.jobTag.length')
            canvas.roundRectColor(30,220,260,this.data.jobInfo.jobTag.length <= 3 ? 70 : 100,12,'#FAFAFC')
            // 公司名字
            canvas.fillText(this.data.jobInfo.serveCompanyName.length > 10 ? (this.data.jobInfo.serveCompanyName.slice(0,15) + '...') : this.data.jobInfo.serveCompanyName,40,245,'#202536',12,'left')
            canvas.fillText(this.data.jobInfo.salary + this.data.jobInfo.jobSalaryType,280,245,'#FF7642',12,'right',true)
            let keyLeft = 40
            for(const i in this.data.jobInfo.jobTag){
                canvas.roundRectColor(keyLeft,260,((this.data.jobInfo.jobTag[i].length + 1) * 10),20,0,'#FAEDEC')
                canvas.fillText(this.data.jobInfo.jobTag[i],keyLeft + (this.data.jobInfo.jobTag[i].length * 13) / 2,273 ,'#FF7642',10,'center')
                console.log(i,keyLeft,'标签')
                keyLeft += (this.data.jobInfo.jobTag[i].length + 1) * 10 + 10
            }
            await wait(100)
            // 底部介绍卡片
            canvas.roundRectColor(15,350,20,105,12,'#ffffff')
            canvas.roundRectColor(285,350,20,105,12,'#ffffff')
            canvas.roundRectColor(20,350,279,105,0,'#ffffff')
            // 头像
            canvas.drawRoundImage(30,360,35,path,'#ffffff')
            // 姓名
            canvas.fillText(user.companyName.length > 10 ? (user.companyName.slice(0,10) + '...') : user.companyName,70,383,'#202536',12,'left',true)
            // 提示
            canvas.fillText('1对1服务 靠谱好工作',30,412,'#9497B1',10,'left')
            // 二维码
            await wait(100)
            canvas.drawHeightCutImage(202,363,80,80,80,this.data.qrcode)
            // 提示扫码
            canvas.drawHeightCutImage(30,424,120,18,18,'/packageRecruit/assets/img/poster/tips.png')
            canvas.fillText('子弹saas提供技术支持',160,480,'#797C86',11,'center')
            ctx.draw(true)
            ctx.restore()
            await wait(100)
            await wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 320,
                height: 500,
                canvasId: 'myCanvas',
                success: async(res)=> {
                    console.log(res,'转换成功',bg[index])
                    await wxfileTobase64(res.tempFilePath,true).then(async url=>{
                        // console.log(url,'url')
                        let arr = []
                        arr = this.data.posterList
                        arr.push({
                            path:res.tempFilePath,
                            src:url
                        })
                        console.log(arr,'arrarrarr',arr.length)
                        if(arr.length ===3 ){
                            wx.hideLoading()
                        }
                        // console.log(res,'res')
                        await this.setData({
                            posterList:arr,
                        },()=>{
                            // console.log(this.data.posterList,'posterList')
                        })
                    })
                }
            })
        
        }
    },
    // 图片保存
    savecanvas(){
        wx.getSetting({
            success:(res)=>{
                wx.authorize({
                    scope:'scope.writePhotosAlbum',
                    success:(res)=> {
                        console.log(res,'res')
                        console.log(this.data.posterList[this.data.currentIndex].path + '','路径')
                        wx.saveImageToPhotosAlbum({
                            filePath:this.data.posterList[this.data.currentIndex].path + '',
                            success:()=>{
                                toast('保存成功')
                            },
                            fail:(rjs)=>{
                                console.log(rjs,'rej3')
                            }
                        })
                    },
                    fail(rej){
                        console.log(rej,'rej2')
                    }
                })
            },
            fail(rej){
                console.log(rej,'rej1')
            }
        })
    },
    preservation(){
        this.savecanvas('保存成功','保存失败')
    },
    onToBrother(){
        this.savecanvas('保存成功，请自行发送到朋友圈','保存失败')
    },
    // onShareAppMessage() {
    //     // scene path: '/pages/index/index?scene=' + encodeURIComponent('uId=' + user.userId + '&cId=' + user.companyId),
    //     return { 
    //         title: '「' + user.userName + '」' + ' 邀请您使用子弹发薪',
    //         path: '/packageActivity/pages/spread/spread?scene=' + encodeURIComponent('QRID=' + this.data.qrId ),
    //         imageUrl: '/packageActivity/assets/img/poster/invitation.png'
    //     }
    // }

})